/* 
 *  HTTP请求函数
 *  开发：Amron
 *  日期：6-22
 */

import Ajax from "./AjaxClass";

export const ajax = (url,options) => {
    let xhr;
    const p = new Promise((resolve,reject) => {
        xhr = new Ajax(url,{
            ...options,
            success:(response) => {
                resolve(response.data);
            },
            requestError:(xhr) => reject({error:'请求失败',xhr}),
            responseError:(status,xhr) => reject({error:'响应失败',status,xhr}),
            timeout:(xhr) => reject({error:'请求超时',xhr}),
            abort:(xhr) => reject({error:'请求中止',xhr})
        })
    });
    // 将xhr实例的xhr对象添加到p上，为了使用abort
    p.xhr = xhr.xhr;
    return p
}

export const get = (url,options) => {
    return ajax(url,{...options,method:'get'});
}

export const getJson = (url,options) => {
    return ajax(url,{...options,method:'get',responseType:'json'});
}

